<!--
 * @Description: 描述
 * @Author: liym
 * @Date: 2025-05-10 15:59:02
 * @LastEditors: liym
 * @LastEditTime: 2025-05-12 15:55:19
-->
<template>
  <view class="container">
    <view class="form-item">
      <text class="label">金额</text>
      <input v-model="form.amount" type="number" placeholder="请输入金额" />
    </view>

  <!--  <view class="form-item">
      <text class="label">订单编号</text>
      <input v-model="form.orderNumber" type="text" placeholder="请输入订单编号" />
    </view> -->

    <view class="form-item">
      <text class="label">服务商ID</text>
      <div class="form-item__content">
        <input class="form-item__input" :value="form.agentId" disabled placeholder="请上传二维码识别服务商ID" />
        <button type="primary" size="mini" @click="scanProviderId">上传识别</button>
      </div>
      
    </view>

    <view class="form-item">
      <button type="primary" @click="submitForm">提交</button>
    </view>
  </view>
</template>

<script>
import { adminRedirectionMixin } from '@/common/commonMixins.js';
import { addOrderApi, updateOrderApi } from '@/api';
import { BrowserQRCodeReader } from '@zxing/library';
export default {
  mixins: [adminRedirectionMixin],
  data() {
    return {
      orderInfo: null,
      form: {
        "id": undefined,
        // "orderNumber": "",
        "agentId": null,
        "amount": null,
      }
    }
  },
  computed: {
    type () {
      if (this.orderInfo === null) return 'add'

      return 'edit'
    }
  },
  mounted () {
    this.orderInfo = uni.getStorageSync('order')
    if (this.orderInfo !== null) {
      const {id, agentId, amount} = this.orderInfo
      this.form = {
        id, agentId, amount
      }
    }
  },
  methods: {
    scanProviderId() {
      uni.chooseImage({
        count: 1,
        success: async (res) => {
          const filePath = res.tempFilePaths[0]
          this.imageSrc = filePath

          // H5 平台支持 file 对象访问
          if (res.tempFiles && res.tempFiles.length > 0) {
            const file = res.tempFiles[0]
            const img = new Image()
            img.src = URL.createObjectURL(file)

            img.onload = async () => {
              try {
                const codeReader = new BrowserQRCodeReader()
                const result = await codeReader.decodeFromImageElement(img)
                this.form.agentId = result.getText()
              } catch (err) {
                console.error('解析失败', err)
                uni.showToast({
                  title: '解析失败',
                  icon: 'none'
                });
                // this.result = '二维码识别失败'
              }
            }
          } else {
            uni.showToast({
              title: '解析失败',
              icon: 'none'
            })
            // this.result = 'H5 平台支持更好，App/小程序不支持 @zxing/library'
          }
        },
        fail: () => {
          // this.result = '图片选择失败'
          uni.showToast({
            title: '图片选择失败',
            icon: 'none'
          })
        }
      })
    },
    async submitForm() {
      const { amount, agentId } = this.form
      if (!amount || !agentId) {
        uni.showToast({ title: '请填写完整信息', icon: 'none' })
        return
      } else {
        // 判断金额是否为合法的正浮点数
        const amountNum = parseFloat(amount)
        if (isNaN(amountNum) || amountNum <= 0 || !/^\d+(\.\d{1,2})?$/.test(amount)) {
          uni.showToast({ title: '请输入合法金额（最多两位小数）', icon: 'none' })
          return
        }
      }

      try {
        uni.showLoading({
						title: '提交中',
						mask: true
        });
        console.log(this.type)
        if (this.type === 'add') {
          await addOrderApi({
            ...this.form,
            amount: parseFloat(amount)
          })
        } else {
          await updateOrderApi({
            ...this.form,
            amount: parseFloat(amount)
          })
        }
        
        uni.hideLoading()
        uni.showToast({ title: '提交成功', icon: 'success' })
        uni.redirectTo({
          url: `/pages/admin/orders`,
        
        });

        console.log('提交内容：', this.form)
      } catch {
        uni.hideLoading()
      }
      
      
    }
  }
}
</script>

<style scoped lang="scss">
.container {
  padding: 20rpx;
}
.form-item {
  margin-bottom: 20rpx;
  &__input {
    flex: 1;
  }
  &__content {
    display: flex;
    align-items: center;
    gap: 20rpx;
  }
}
.label {
  display: block;
  margin-bottom: 10rpx;
  font-weight: bold;
}
input {
  border: 1px solid #ccc;
  border-radius: 8rpx;
  padding: 16rpx;
}
</style>
